import { isObject } from "./is";

/**
 * Add the object as a parameter to the URL
 * @param baseUrl url
 * @param obj
 * @returns {string}
 * eg:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams(baseUrl: string, obj: any): string {
  let parameters = "";
  for (const key in obj) {
    parameters += key + "=" + encodeURIComponent(obj[key]) + "&";
  }
  parameters = parameters.replace(/&$/, "");
  return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, "?") + parameters;
}

// 深度合并
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string;
  for (key in target) {
    src[key] = isObject(src[key]) ? deepMerge(src[key], target[key]) : (src[key] = target[key]);
  }
  return src;
}

/**
 * 获取assets/images下的图片路径
 * @param string：匹配的图片路径字符串
 * @returns [path]
 */
export function getImgByUrl(dirPath: string) {
  const glods = import.meta.glob(`@/assets/images/**/*`, {
    eager: true
  });
  let imgObj = {};
  for (const key in glods) {
    if (key.includes(dirPath)) {
      const keyName = key?.split("/")?.pop()?.split(".")[0];
      const keys = glods[key] as Record<string, any>;
      imgObj[keyName as string] = keys?.default;
    }
  }
  return imgObj;
}


export function detectDevice() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

  // Windows Phone 必须优先检测，因为其 UA 也包含 Android
  if (/windows phone/i.test(userAgent)) {
    return "Windows Phone";
  }

  // Android终端或者UC浏览器
  if (/android/i.test(userAgent)) {
    return "Android";
  }

  // iOS终端
  if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    return "iOS";
  }

  // 其他设备
  return "PC";
}
